package com.xoa.service.cms.core;

import com.hp.hpl.sparta.Document;
import com.xoa.model.cms.CmsChannelInfo;
import com.xoa.model.cms.CmsSiteInfo;
import com.xoa.model.cms.SiteTemplateModel;
import com.xoa.service.cms.CmsChannelService;
import com.xoa.service.cms.CmsDocumentService;
import com.xoa.service.cms.CmsSiteService;
import com.xoa.service.cms.CmsSiteTemplateService;
import com.xoa.service.enclosure.EnclosureService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;
import java.util.Map;
import java.util.ResourceBundle;

/**
* @author 程叶同
* @date 2018/8/13 14:45
* @desc
*/
@Repository
public class CmsPublisher {
    @Autowired
    private CmsSiteService siteService;

    @Autowired
    private CmsSiteTemplateService siteTemplateService;

    @Autowired
    private CmsChannelService channelService;

    @Autowired
    private CmsDocumentService documentService;

    @Autowired
    private EnclosureService attachmentService;

    public void pubSite(HttpServletRequest request,HttpServletResponse response,int siteId){
        CmsSiteInfo siteInfo = siteService.getSiteInfo(siteId);
        //首页模板
        SiteTemplateModel indexPage = siteTemplateService.getSiteTemplate(siteInfo.getIndexTpl());
        String renderContent = renderSiteIndexPage(request,response,siteId,null,false);

    }

    public void pubSiteIndex(int siteId){

    }

    public void pubChannel(int channelId){

    }

    public void pubChannelIndex(int channelId){

    }

    public void pubDoc(int chnlDocId){

    }

    /**
     *渲染站点
     * @param siteId
     * @return
     */
    public String renderSiteIndexPage(HttpServletRequest request, HttpServletResponse response,int siteId, Map params, boolean previewFlag){
        //获取站点信息
        CmsSiteInfo siteModel = siteService.getSiteInfo(siteId);
        // 判断是否是预览 如果不是预览判断是否是已经发布的站点
        if(!previewFlag){
            Integer pubStatus = siteModel.getPubStatus();
            if(pubStatus!=null&&pubStatus==0){
                return "<h1>没有找到页面，请联系管理员</h1>";
            }
        }
        //获取站点模板
        SiteTemplateModel indexTpl=null;
        if(siteModel.getIndexTpl()!=null) {
            indexTpl= siteTemplateService.getSiteTemplate(siteModel.getIndexTpl());
        }else{
            indexTpl=null;
        }
        if(indexTpl==null){
         return null;
        }
        //获取本地库
        String dateSouse ="xoa"+(String)request.getSession().getAttribute("loginDateSouse");

        if(indexTpl!=null){//如果存在首页模板，则进行渲染
           // String path = TeeSysProps.getSiteTemplatePath()+File.separator+indexTpl.getSiteId();
//            ResourceBundle rb =  ResourceBundle.getBundle("cms");
            String pathsrc=request.getRealPath("cmstpls");
            String path = pathsrc+ System.getProperty("file.separator")+dateSouse+ System.getProperty("file.separator")+indexTpl.getSiteId();
            Configuration config=new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            try {
                config.setDirectoryForTemplateLoading(new File(path));
                //注入服务
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService", siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);
                config.setCustomAttribute("attachmentService", attachmentService);

                //附加参数
                config.setCustomAttribute("ROOT_PATH", "./");
                config.setCustomAttribute("SITE_ID", siteModel.getSid());

                config.setCustomAttribute("preview", true);

                Template template=config.getTemplate(indexTpl.getTplFileName(),"UTF-8");
                baos = new ByteArrayOutputStream();
                out = new OutputStreamWriter(baos);

                //输出参数
                template.process(CmsTemplateUtil.getInstance(), out);
                out.flush();
                out.close();
                return baos.toString();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(baos!=null){
                    try {
                        baos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
            }
        }
        return null;
    }

    /**
     * 渲染栏目
     * @param channelId
     * @return
     */
    public String renderChannelIndexPage(HttpServletRequest request,int channelId, Map params, boolean previewFlag){
        //获取站点信息
        CmsChannelInfo channelInfo = channelService.getChannelInfo(channelId);
        //获取站点信息
        CmsSiteInfo siteInfo = siteService.getSiteInfo(channelInfo.getSiteId());
        //获取站点模板
        SiteTemplateModel indexTpl = siteTemplateService.getSiteTemplate(channelInfo.getIndexTpl());

        //获取本地库
        String dateSouse ="xoa"+(String)request.getSession().getAttribute("loginDateSouse");

        if(indexTpl!=null){//如果存在首页模板，则进行渲染
//            String path = TeeSysProps.getSiteTemplatePath()+File.separator+indexTpl.getSiteId();
//            ResourceBundle rb =  ResourceBundle.getBundle("cms");
            String pathsrc=request.getRealPath("cmstpls");
            String path = pathsrc+ System.getProperty("file.separator")+dateSouse+System.getProperty("file.separator")+indexTpl.getSiteId();
            Configuration config=new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            try {
                config.setDirectoryForTemplateLoading(new File(path));

                int curPage = FileUtils.getInteger(params.get("curPage"), 1);

                //注入服务
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService", siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);
                config.setCustomAttribute("attachmentService", attachmentService);

                //附加参数
                config.setCustomAttribute("ROOT_PATH", channelService.getChannelRootPath(channelId));
                config.setCustomAttribute("SITE_ID", channelInfo.getSiteId());
                config.setCustomAttribute("CHANNEL_ID", channelId);
                config.setSharedVariable("curChannelId", channelId);


                config.setCustomAttribute("preview", true);
                config.setCustomAttribute("curPage", curPage);

                //获取当前栏目下的可发布的文档数量
                int pageSize = channelInfo.getPageSize();
                long total = documentService.getPublishableDocumentsCountByChnlId(channelId);
                int pageNums = 0;
                if(total!=0 && pageSize!=0){
                    pageNums = (int) ((total)%pageSize==0?(total)/pageSize:(total)/pageSize+1);
                }

                config.setCustomAttribute("pageNums", pageNums);

                Template template=config.getTemplate(indexTpl.getTplFileName(),"UTF-8");
                baos = new ByteArrayOutputStream();
                out = new OutputStreamWriter(baos,"UTF-8");

                //输出参数
                template.process(CmsTemplateUtil.getInstance(), out);
                out.flush();
                out.close();
                return baos.toString("UTF-8");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(baos!=null){
                    try {
                        baos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
            }
        }
        return null;
    }

    /**
     * 渲染文档详细页面
     * @param
     * @return
     */
    public String renderDocPage(HttpServletRequest request,int chnlDocId, Map params, boolean previewFlag) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
        Map cd = documentService.getDocumentByChnlDocId(chnlDocId);
        CmsChannelInfo channelInfo = null;
        channelInfo = channelService.getChannelInfo(FileUtils.getInteger(cd.get("chnlId0"), 0));
        //获取站点信息
        CmsSiteInfo siteInfo = siteService.getSiteInfo(channelInfo.getSiteId());
        //获取站点模板
        SiteTemplateModel detailTpl = siteTemplateService.getSiteTemplate(channelInfo.getDetailTpl());

        //获取本地库

        String dateSouse ="xoa"+(String)request.getSession().getAttribute("loginDateSouse");
        if(detailTpl!=null){//如果存在首页模板，则进行渲染
//            String path = TeeSysProps.getSiteTemplatePath()+File.separator+detailTpl.getSiteId();
//            ResourceBundle rb =  ResourceBundle.getBundle("cms");
            String pathsrc=request.getRealPath("cmstpls");
            String path = pathsrc+ System.getProperty("file.separator")+dateSouse+ System.getProperty("file.separator")+detailTpl.getSiteId();
            Configuration config=new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            try {
                config.setDirectoryForTemplateLoading(new File(path));

                //注入服务
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService", siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);
                config.setCustomAttribute("attachmentService", attachmentService);

                //附加参数
                config.setCustomAttribute("ROOT_PATH", channelService.getChannelRootPath(channelInfo.getSid()));
                config.setCustomAttribute("SITE_ID", channelInfo.getSiteId());
                config.setCustomAttribute("CHANNEL_ID", channelInfo.getSid());
                config.setSharedVariable("curChannelId", channelInfo.getSid());
                config.setCustomAttribute("DOCUMENT_ID", cd.get("docId"));
                config.setCustomAttribute("CHNLDOC_ID", chnlDocId);

                config.setCustomAttribute("preview", true);

                Template template=config.getTemplate(detailTpl.getTplFileName(),"UTF-8");
                baos = new ByteArrayOutputStream();
                out = new OutputStreamWriter(baos,"UTF-8");

                //输出参数
                template.process(CmsTemplateUtil.getInstance(), out);

                out.flush();
                out.close();
                return baos.toString("UTF-8");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(baos!=null){
                    try {
                        baos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                }
            }
        }
        return null;
    }
}
